package com.ruoyi.framework.aspectj;

import com.ruoyi.common.annotation.DefaultSaleId;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Aspect
@Component
public class DefaultSaleIdAspect {

    @Autowired
    private SysUserMapper userMapper;

    @Before("@annotation(defaultSaleId) && args(entity,..)")
    public void setDefaultValues(JoinPoint joinPoint, DefaultSaleId defaultSaleId, Object entity) throws IllegalAccessException {
        // 设置 saleId 字段为 1
        Field saleIdField = getField(entity.getClass(), "saleId");
        Field saleIdsField = getField(entity.getClass(), "saleIds");
        Field deptIdField = getField(entity.getClass(), "deptId");
        if (saleIdField != null) {
            List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
            if (roles == null || roles.size() == 0) {
                throw new ServiceException("提示：请联系管理员为当前用户添加角色");
            }
            List<String> roleKeys = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
            if (roleKeys.size() == 0) {
                throw new ServiceException("提示：请联系管理员为当前用户角色添加roleKey值");
            }
            // 假设我们要过滤掉所有长度小于5的字符串
            List<String> roleKeyDataFilter = roleKeys.stream()
                    .filter(s -> !s.equals("salesman") && !s.equals("manage") )
                    .collect(Collectors.toList());

            if(roleKeyDataFilter != null && roleKeyDataFilter.size() > 0){
                deptIdField.setAccessible(true);
                if(deptIdField != null && deptIdField.get(entity) != null){
                    Map<String, Object> map = new HashMap<>();

                    map.put("deptId", deptIdField.get(entity));
                    map.put("roleKey", "salesman");
                    List<Long> saleIds = userMapper.selectAllMangageSaleUserListByDeptId(map);
                    String vstrIds = saleIds.stream().map(String::valueOf).collect(Collectors.joining(","));
                    saleIdsField.setAccessible(true);
                    saleIdsField.set(entity, vstrIds);
                }
            }else {
                if (roleKeys.contains("salesman") || roleKeys.contains("manage")) {
                    if (roleKeys.contains("manage")) {
                        Map<String, Object> map = new HashMap<>(2);
                        map.put("userId", SecurityUtils.getLoginUser().getUserId());
                        map.put("roleKey", "salesman");
                        List<Long> saleIds = userMapper.selectAllMangageSaleUserListByUserId(map);
                        String vstrIds = saleIds.stream().map(String::valueOf).collect(Collectors.joining(","));
                        saleIdsField.setAccessible(true);
                        saleIdsField.set(entity, vstrIds);
                    }else{
                        saleIdField.setAccessible(true);
                        saleIdField.set(entity, SecurityUtils.getLoginUser().getUserId());
                    }
                }
            }
        }
    }

    private Field getField(Class<?> clazz, String fieldName) {
        try {
            return clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            // 如果字段不存在，返回 null
            return null;
        }
    }
}
